package com.tanhua.dubbo.api;

import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.model.domain.PageResult;
import com.tanhua.model.domain.mongo.FocusUser;
import com.tanhua.model.domain.mongo.Video;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @author lk
 * @date 2022-04-03
 */
@DubboService
public class VideoApiImpl implements VideoApi{
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private MongoTemplate mongoTemplate;

    //发布小视频
    @Override
    public void save(Video video) {
        video.setVid(idWorker.getNextId("video"));
        mongoTemplate.save(video);
    }

    //根据vid查询数据列表
    @Override
    public List<Video> findVideo(List<Long> collect) {
        Query query = Query.query(Criteria.where("id").in(collect));
        List<Video> videoList = mongoTemplate.find(query, Video.class);
        return videoList;
    }

    //分页查询数据列表
    @Override
    public List<Video> queryVideoList(int page, Integer pagesize) {
        Query query = new Query().skip((page - 1) * pagesize).limit(pagesize).with(Sort.by(Sort.Order.desc("created")));
        List<Video> videoList = mongoTemplate.find(query, Video.class);
        return videoList;
    }

    //查询指定用户发布的所有视频列表
    @Override
    public PageResult findByUserId(Integer page, Integer pagesize, Long userId) {
        //视频数量
        Query query = Query.query(Criteria.where("userId").is(userId));
        long count = mongoTemplate.count(query, Video.class);
        //视频详情
        query.skip((page - 1) * pagesize).limit(pagesize).with(Sort.by(Sort.Order.desc("created")));
        List<Video> videoList = mongoTemplate.find(query, Video.class);
        return new PageResult(page,pagesize,(int)count,videoList);
    }

    //关注视频作者
    @Override
    public void saveFollowUser(FocusUser focusUser) {
        mongoTemplate.save(focusUser);
    }

    //取消关注视频作者
    @Override
    public void deleteFollowUser(Long followUserId, Long userId) {
        Query query = Query.query(Criteria.where("userId").is(userId).and("followUserId").is(followUserId));
        mongoTemplate.remove(query,FocusUser.class);
    }

}
